﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Windows.Forms;
using ERP_SaaS_WinForm.登录.Common;
using ERP_SaaS_WinForm.生产计划_派单_车间.apollo;

namespace ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest
{
    /// <summary>
    /// API请求帮助类
    /// 封装HTTP请求的通用方法
    /// </summary>
    public class ApiRequestHelper
    {
        private   string urls;
        public  ApiRequestHelper()
        {
            urls = ProductionConfig.ApiBaseUrl;
        }
        private static readonly HttpClient _httpClient;
        private static readonly string BaseUrl;
        private const int DefaultTimeout = 30; // 默认超时时间30秒

        static ApiRequestHelper()
        {
                BaseUrl = ProductionConfig.ApiBaseUrl;
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(DefaultTimeout);
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            
            // 自动设置JWT token（如果已登录）
            if (TokenDto.IsLoggedIn)
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenDto.JwtToken);
            }
        }

        /// <summary>
        /// 设置认证Token
        /// </summary>
        /// <param name="token">JWT Token</param>
        public static void SetAuthorizationToken(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }
        }

        /// <summary>
        /// 清除认证Token
        /// </summary>
        public static void ClearAuthorizationToken()
        {
            _httpClient.DefaultRequestHeaders.Authorization = null;
        }

        /// <summary>
        /// 更新JWT Token（从登录模块获取）
        /// </summary>
        public static void UpdateJwtToken()
        {
            if (TokenDto.IsLoggedIn)
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenDto.JwtToken);
            }
            else
            {
                _httpClient.DefaultRequestHeaders.Authorization = null;
            }
        }

        /// <summary>
        /// 检查是否已登录
        /// </summary>
        /// <returns>是否已登录</returns>
        public static bool IsLoggedIn()
        {
            return TokenDto.IsLoggedIn;
        }

        /// <summary>
        /// GET请求
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="endpoint">API端点</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>API响应结果</returns>
        public static async Task<ApiResponse<T>> GetAsync<T>(string endpoint, Dictionary<string, string> parameters = null)
        {
            try
            {
                // 检查登录状态并更新JWT token
                if (!IsLoggedIn())
                {
                    return new ApiResponse<T>
                    {
                        Success = false,
                        Message = "用户未登录，请先登录",
                        Data = default(T)
                    };
                }
                
                UpdateJwtToken();
                
                string url = BuildUrl(endpoint, parameters);
                Console.WriteLine($"GET请求URL: {url}");

                var response = await _httpClient.GetAsync(url);
                return await ProcessResponse<T>(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GET请求异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    Success = false,
                    Message = $"请求失败: {ex.Message}",
                    Data = default(T)
                };
            }
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="endpoint">API端点</param>
        /// <param name="data">请求数据</param>
        /// <returns>API响应结果</returns>
        public static async Task<ApiResponse<T>> PostAsync<T>(string endpoint, object data)
        {
            try
            {
                // 检查登录状态并更新JWT token
                if (!IsLoggedIn())
                {
                    return new ApiResponse<T>
                    {
                        Success = false,
                        Message = "用户未登录，请先登录",
                        Data = default(T)
                    };
                }
                
                UpdateJwtToken();
                
                string url = BuildUrl(endpoint);
                string jsonContent = JsonConvert.SerializeObject(data);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                Console.WriteLine($"POST请求URL: {url}");
                Console.WriteLine($"POST请求数据: {jsonContent}");

                var response = await _httpClient.PostAsync(url, content);
                return await ProcessResponse<T>(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"POST请求异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    Success = false,
                    Message = $"请求失败: {ex.Message}",
                    Data = default(T)
                };
            }
        }

        /// <summary>
        /// PUT请求
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="endpoint">API端点</param>
        /// <param name="data">请求数据</param>
        /// <returns>API响应结果</returns>
        public static async Task<ApiResponse<T>> PutAsync<T>(string endpoint, object data)
        {
            try
            {
                // 检查登录状态并更新JWT token
                if (!IsLoggedIn())
                {
                    return new ApiResponse<T>
                    {
                        Success = false,
                        Message = "用户未登录，请先登录",
                        Data = default(T)
                    };
                }
                
                UpdateJwtToken();
                
                string url = BuildUrl(endpoint);
                string jsonContent = JsonConvert.SerializeObject(data);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                Console.WriteLine($"PUT请求URL: {url}");
                Console.WriteLine($"PUT请求数据: {jsonContent}");

                var response = await _httpClient.PutAsync(url, content);
                return await ProcessResponse<T>(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"PUT请求异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    Success = false,
                    Message = $"请求失败: {ex.Message}",
                    Data = default(T)
                };
            }
        }

        /// <summary>
        /// DELETE请求
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="endpoint">API端点</param>
        /// <returns>API响应结果</returns>
        public static async Task<ApiResponse<T>> DeleteAsync<T>(string endpoint)
        {
            try
            {
                // 检查登录状态并更新JWT token
                if (!IsLoggedIn())
                {
                    return new ApiResponse<T>
                    {
                        Success = false,
                        Message = "用户未登录，请先登录",
                        Data = default(T)
                    };
                }
                
                UpdateJwtToken();
                
                string url = BuildUrl(endpoint);
                Console.WriteLine($"DELETE请求URL: {url}");

                var response = await _httpClient.DeleteAsync(url);
                return await ProcessResponse<T>(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DELETE请求异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    Success = false,
                    Message = $"请求失败: {ex.Message}",
                    Data = default(T)
                };
            }
        }

        /// <summary>
        /// 构建完整URL
        /// </summary>
        /// <param name="endpoint">API端点</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>完整URL</returns>
        private static string BuildUrl(string endpoint, Dictionary<string, string> parameters = null)
        {
            string url = $"{BaseUrl}/{endpoint.TrimStart('/')}";
            
            if (parameters != null && parameters.Count > 0)
            {
                var queryString = new List<string>();
                foreach (var param in parameters)
                {
                    if (!string.IsNullOrEmpty(param.Value))
                    {
                        queryString.Add($"{Uri.EscapeDataString(param.Key)}={Uri.EscapeDataString(param.Value)}");
                    }
                }
                
                if (queryString.Count > 0)
                {
                    url += "?" + string.Join("&", queryString);
                }
            }
            
            return url;
        }

        /// <summary>
        /// 处理HTTP响应
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="response">HTTP响应</param>
        /// <returns>API响应结果</returns>
        private static async Task<ApiResponse<T>> ProcessResponse<T>(HttpResponseMessage response)
        {
            try
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"响应状态码: {response.StatusCode}");
                Console.WriteLine($"响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        var result = JsonConvert.DeserializeObject<T>(responseContent);
                        return new ApiResponse<T>
                        {
                            Success = true,
                            Message = "请求成功",
                            Data = result,
                            StatusCode = (int)response.StatusCode
                        };
                    }
                    catch (JsonException ex)
                    {
                        Console.WriteLine($"JSON反序列化失败: {ex.Message}");
                        return new ApiResponse<T>
                        {
                            Success = false,
                            Message = $"数据解析失败: {ex.Message}",
                            Data = default(T),
                            StatusCode = (int)response.StatusCode
                        };
                    }
                }
                else
                {
                    // 处理401未授权错误
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return new ApiResponse<T>
                        {
                            Success = false,
                            Message = "登录已过期，请重新登录",
                            Data = default(T),
                            StatusCode = (int)response.StatusCode,
                            ErrorCode = 401
                        };
                    }
                    
                    return new ApiResponse<T>
                    {
                        Success = false,
                        Message = $"HTTP错误: {response.StatusCode} - {responseContent}",
                        Data = default(T),
                        StatusCode = (int)response.StatusCode
                    };
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理响应异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    Success = false,
                    Message = $"响应处理失败: {ex.Message}",
                    Data = default(T)
                };
            }
        }

        /// <summary>
        /// 显示错误消息
        /// </summary>
        /// <param name="message">错误消息</param>
        /// <param name="title">标题</param>
        public static void ShowError(string message, string title = "错误")
        {
            MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 显示成功消息
        /// </summary>
        /// <param name="message">成功消息</param>
        /// <param name="title">标题</param>
        public static void ShowSuccess(string message, string title = "成功")
        {
            MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 显示警告消息
        /// </summary>
        /// <param name="message">警告消息</param>
        /// <param name="title">标题</param>
        public static void ShowWarning(string message, string title = "警告")
        {
            MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public static void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

    /// <summary>
    /// API响应结果类
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    public class ApiResponse<T>
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 响应消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 响应数据
        /// </summary>
        public T Data { get; set; }

        /// <summary>
        /// HTTP状态码
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// 错误代码
        /// </summary>
        public int? ErrorCode { get; set; }
    }

    /// <summary>
    /// 分页请求参数
    /// </summary>
    public class PagingRequest
    {
        /// <summary>
        /// 页码（从1开始）
        /// </summary>
        public int PageIndex { get; set; } = 1;

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize { get; set; } = 20;

        /// <summary>
        /// 搜索关键词
        /// </summary>
        public string SearchKeyword { get; set; }

        /// <summary>
        /// 排序字段
        /// </summary>
        public string SortField { get; set; }

        /// <summary>
        /// 排序方向（asc/desc）
        /// </summary>
        public string SortDirection { get; set; } = "asc";
    }

    /// <summary>
    /// 分页响应结果
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    public class PagingResponse<T>
    {
        /// <summary>
        /// 数据列表
        /// </summary>
        public List<T> Data { get; set; } = new List<T>();

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages { get; set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage { get; set; }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 是否有上一页
        /// </summary>
        public bool HasPreviousPage => CurrentPage > 1;

        /// <summary>
        /// 是否有下一页
        /// </summary>
        public bool HasNextPage => CurrentPage < TotalPages;
    }
}
